import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
import 'assets/js/bootstrap-switch.min.js'
import 'assets/css/bootstrap-switch.min.css'

declare var $: any
@Component({
  selector: 'sa-repair-plan',
  templateUrl: './repair-plan.component.html',
  styleUrls: ['./repair-plan.component.css']
})
export class RepairPlanComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      scenarioName: {
        validators: {
          notEmpty: {
            message: '请输入维修方案名称'
          },
          stringLength: {
            max: 30,
            message: '维修方案名称30字以内'
          },
          remote: {
            message: '维修方案名称已存在,请输入新的维修方案名称',
            url: config.BaseURL + 'repairPlan/verifyScenarioName.html',
            // type: 'post',
            data: function (validator) {
              return {
                id: validator.getFieldElements('scenarioName').attr('rowId')
              }
            }
          }
        }
      },
      companyName: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择所属厂区'
          }
        }
      }
    }
  }
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  tableParam: any = {
    scenarioName: '',
    searchKey: '',
    startTime: '',
    endTime: '',
    status: '',
    companyId: '',
    companyName: '',
    sortBy: '',
    sortType: '1'
  }
  repairPointList: any = [] // 维修方案名称
  pageType: string = '新增'
  repairPlans: any = [
    {
      costDetail: '移机-散装',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '移机',
      index: '1',
      unit: '次'
    },
    {
      costDetail: '移机-袋装',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '移机',
      index: '2',
      unit: '次'
    },
    {
      costDetail: '更换-传感器',
      discount: 1,
      restrict: 1,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '设备维护',
      index: '3',
      unit: '片'
    },
    {
      costDetail: '更换-天线',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '设备维护',
      index: '4',
      unit: '个'
    },
    {
      costDetail: '更换-线材',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '设备维护',
      index: '5',
      unit: '套'
    },
    {
      costDetail: '更换-主机',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '设备维护',
      index: '6',
      unit: '个'
    },
    {
      costDetail: '更换-保险',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '设备维护',
      index: '7',
      unit: '个'
    },
    {
      costDetail: '维修工时',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '维修工时',
      index: '8',
      unit: '次'
    },
    {
      costDetail: '加挂-散装',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '加挂',
      index: '9',
      unit: '次'
    },
    {
      costDetail: '加挂-袋装',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '加挂',
      index: '10',
      unit: '次'
    },
    {
      costDetail: '其他',
      discount: 1,
      restrict: 0,
      discountPrice: 0,
      enabled: 1,
      price: 0,
      typeCost: '其他',
      index: '11',
      unit: ''
    }
  ]
  repairPonitFrom: any = {
    id: undefined,
    scenarioName: '',
    scenarioNumber: '',
    companyArrays: [],
    companyId: '',
    status: '1',
    showDetail: '1',
    needCheck: '1',
    needAppointment: '0',
    repairPlans: [],
    payWay: '0'
  }
  repairPlansAttr: any = []

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  companySelected(data) {
    this.tableParam.companyId = data.companyId || ''
    this.tableParam.companyName = data.companyName
  }
  addCompanySelected(data) {
    this.repairPonitFrom.companyId = data.companyIdSelectedList.join(',')
  }
  // 接收子组件传递过来的数据
  getSelectTableTime(time) {
    this.tableParam.startTime = time.startTime
    this.tableParam.endTime = time.endTime
  }
  ngOnInit() {
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        this.initAllRepairPoint().then(() => {
          this.initRepairPointSelect2()
        })
      })
    })
    this.load()
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  tableSearch() {
    this.curPage = 1
    this.load()
  }
  //删除
  tableDel(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http('repairPlan/deleteById.html', 'id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  isSwitch: boolean = false //默认隐藏
  //初始化加载list数据
  load() {
    let timeCheck = common.correctTimeParams(this.tableParam.startTime, this.tableParam.endTime, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        scenarioName: this.tableParam.scenarioName,
        companyId: this.tableParam.companyId,
        startTime: this.tableParam.startTime,
        endTime: this.tableParam.endTime,
        status: this.tableParam.status,
        sortBy: this.tableParam.sortBy,
        sortType: this.tableParam.sortType,
        searchKey: common.stringTrim(this.tableParam.searchKey)
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('repairPlan/queryRepairPlan.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  // 初始化switch
  // index: any = 0;
  // aniFun() {
  //     let that = this;
  //     let length = $('.isStatus').length;
  //     if (length > 30 && this.index < 30) {
  //         $('.isStatus:lt(50)').bootstrapSwitch({    //初始化按钮
  //             onText: "开启",
  //             offText: "关闭",
  //             onColor: "primary",
  //             offColor: "warning",
  //             onSwitchChange: function (event, state) {
  //                 if (state == true) {
  //                     that.checkStatus('1', event.target.attributes.key.nodeValue);
  //                 } else {
  //                     that.checkStatus('0', event.target.attributes.key.nodeValue);
  //                 }
  //             }
  //         });
  //         this.index = 30;
  //         let ani = window.requestAnimationFrame(that.aniFun.bind(this));
  //     }
  //     $('.isStatus:eq(' + this.index + ')').bootstrapSwitch({    //初始化按钮
  //         onText: "开启",
  //         offText: "关闭",
  //         onColor: "primary",
  //         offColor: "warning",
  //         onSwitchChange: function (event, state) {
  //             if (state == true) {
  //                 that.checkStatus('1', event.target.attributes.key.nodeValue);
  //             } else {
  //                 that.checkStatus('0', event.target.attributes.key.nodeValue);
  //             }
  //         }
  //     });
  //     that.index++;

  //     if (!!$('.isStatus:eq(' + that.index + ')')) {
  //         window.requestAnimationFrame(that.aniFun.bind(this))
  //     }

  // }

  initSwitch() {
    var that = this
    // if ($(".isStatus").length < 30) {
    //     $('.isStatus').bootstrapSwitch({    //初始化按钮
    //         onText: "开启",
    //         offText: "关闭",
    //         onColor: "primary",
    //         offColor: "warning",
    //         onSwitchChange: function (event, state) {
    //             if (state == true) {
    //                 that.checkStatus('1', event.target.attributes.key.nodeValue);
    //             } else {
    //                 that.checkStatus('0', event.target.attributes.key.nodeValue);
    //             }
    //         }
    //     });
    // } else {
    //     this.aniFun()
    // }

    $('.isStatus').bootstrapSwitch({
      //初始化按钮
      onText: '开启',
      offText: '关闭',
      onColor: 'primary',
      offColor: 'warning',
      onSwitchChange: function (event, state) {
        console.log(event, state, 'ddd')
        if (state == true) {
          that.checkStatus('1', event.target.attributes.key.nodeValue)
        } else {
          that.checkStatus('0', event.target.attributes.key.nodeValue)
        }
      }
    })
  }
  //是否启用
  checkStatus(check, string) {
    var that = this
    var str = string.replace(/([^0-9])+/i, '')
    for (var i = 0; i < this.repairPlansAttr.length; i++) {
      if (this.repairPlansAttr[i].index == str) {
        if (string.indexOf('enabled') != -1) {
          this.repairPlansAttr[i].enabled = check
        } else if (string.indexOf('discount') != -1) {
          this.repairPlansAttr[i].discount = check
        } else if (string.indexOf('restrict') != -1) {
          this.repairPlansAttr[i].restrict = check
        }
      }
    }

    that.repairPonitFrom.repairPlans = JSON.parse(JSON.stringify(this.repairPlansAttr))
    let timer = setTimeout(function () {
      that.initSwitch()
      that.isSwitch = true
      clearTimeout(timer)
      timer = null
    }, 1)
  }

  // 新增
  tableAdd(modal) {
    var that = this
    this.pageType = '新增'
    this.repairPlansAttr = JSON.parse(JSON.stringify(this.repairPlans))
    this.repairPonitFrom = {
      id: undefined,
      scenarioName: '',
      scenarioNumber: undefined,
      companyArrays: [],
      companyId: '',
      status: '1',
      showDetail: '1',
      needCheck: '1',
      needAppointment: '0',
      repairPlans: this.repairPlansAttr,
      payWay: '0'
    }

    let timer = setTimeout(function () {
      that.initSwitch()
      that.isSwitch = true
      clearTimeout(timer)
      timer = null
    }, 1)

    $('#repairPointFrom').data('bootstrapValidator').resetForm()
    modal.show()
  }
  // 编辑
  tableEdit(row, modal) {
    $('#repairPointFrom').data('bootstrapValidator').resetForm()
    row = JSON.parse(JSON.stringify(row))
    var that = this
    this.repairPonitFrom.id = row.id
    this.pageType = '编辑'
    this.repairPlansAttr = []
    for (let key in this.repairPonitFrom) {
      this.repairPonitFrom[key] = row[key]
    }
    this.repairPonitFrom.payWay = this.repairPonitFrom.payWay.toString()
    var repairPlans = JSON.parse(JSON.stringify(row.repairPlans))
    for (var i = 0; i < repairPlans.length; i++) {
      repairPlans[i].price = repairPlans[i].price / 100
      repairPlans[i].discountPrice = repairPlans[i].discountPrice / 100
    }
    this.repairPlansAttr = JSON.parse(JSON.stringify(repairPlans))
    let timer = setTimeout(function () {
      that.initSwitch()
      if (row.showDetail == '1') {
        that.isSwitch = true
      } else {
        that.isSwitch = false
      }
      clearTimeout(timer)
      timer = null
    }, 1)
    modal.show()
  }
  // 关闭弹窗
  modalClose(modal) {
    modal.hide()
    this.repairPonitFrom = {
      id: undefined,
      scenarioNumber: undefined,
      scenarioName: '',
      companyArrays: [],
      companyId: '',
      status: '1',
      showDetail: '1',
      needCheck: '1',
      needAppointment: '0',
      repairPlans: [],
      payWay: '0'
    }
    this.isSwitch = false
    $('#repairPointFrom').data('bootstrapValidator').resetForm()
  }
  priceChange(value, index) {
    var num = index - 1
    if (value != 0) {
      if (value < this.repairPlansAttr[num].discountPrice) {
        this.jsonApiService.message('该费用价格需要比减免后的价格高')
        this.repairPlansAttr[num].price = 0
        return
      }
    }
  }
  discountPriceChange(value, index) {
    var num = index - 1
    if (value != 0) {
      if (value > this.repairPlansAttr[num].price) {
        this.jsonApiService.message('该减免价格需要比费用价格的价格低')
        this.repairPlansAttr[num].discountPrice = 0
        return
      }
    }
  }
  // 维修方案提交
  repairPointSubmit(modal) {
    $('#repairPointFrom').bootstrapValidator('validate') //开启验证
    var repairPlans = JSON.parse(JSON.stringify(this.repairPlansAttr))
    for (var i = 0; i < repairPlans.length; i++) {
      if (repairPlans[i].price != 0) {
        repairPlans[i].price = repairPlans[i].price * 100
      }
      if (repairPlans[i].discountPrice != 0) {
        repairPlans[i].discountPrice = repairPlans[i].discountPrice * 100
      }
    }
    this.repairPonitFrom.repairPlans = JSON.stringify(repairPlans)
    let timer = setTimeout(() => {
      let isValid = $('#repairPointFrom').data('bootstrapValidator').isValid() //验证是否通过
      if (isValid) {
        let reqdata = JSON.parse(JSON.stringify(this.repairPonitFrom))
        this.jsonApiService.http_obj('repairPlan/recordChanges.html', reqdata).subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.modalClose(modal)
            this.load()
            this.isSwitch = false
          }
        })
      }
      clearTimeout(timer)
      timer = null
    }, 200)
  }
  // 维修方案数据
  initAllRepairPoint() {
    var that = this
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('repairPlan/getScenarioName.html', null).subscribe(data => {
        if (data.success) {
          var repairPointList = data.data
          var selectdata = []
          for (var i = 0; i < repairPointList.length; i++) {
            var obj = {
              id: repairPointList[i].id,
              text: repairPointList[i].scenarioName
            }
            selectdata[i] = obj
          }
        }
        that.repairPointList = selectdata
        resolve()
      })
    })
  }
  // 维修方案配置
  initRepairPointSelect2() {
    let that = this
    // 维修方案-查询条件
    $('#repairPointSelect2')
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        data: this.repairPointList
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.tableParam.scenarioName = data.text
      })
  }
  // 删除维修方案-查询
  delRepairPoint() {
    this.tableParam.scenarioName = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#repairPointSelect2').val('')
    $('#select2-repairPointSelect2-container').empty()
    $('#select2-repairPointSelect2-container').attr('title', '')
    $('#select2-repairPointSelect2-container').prepend(str)
  }
  companyNames: any = ''
  //方案配置
  viewChanges(row, modal) {
    $('#repairPointFrom').data('bootstrapValidator').resetForm()
    var that = this
    this.pageType = '查看'
    this.repairPlansAttr = []
    for (let key in this.repairPonitFrom) {
      this.repairPonitFrom[key] = row[key]
    }
    this.repairPonitFrom.payWay = this.repairPonitFrom.payWay.toString()
    var repairPlans = JSON.parse(JSON.stringify(row.repairPlans))
    for (var i = 0; i < repairPlans.length; i++) {
      repairPlans[i].price = repairPlans[i].price / 100
      repairPlans[i].discountPrice = repairPlans[i].discountPrice / 100
    }

    this.repairPlansAttr = JSON.parse(JSON.stringify(repairPlans))

    var companyNameAttr = []
    for (var j = 0; j < row.companyArrays.length; j++) {
      companyNameAttr.push(row.companyArrays[j].companyName)
    }
    this.companyNames = companyNameAttr.join(',')

    let timer = setTimeout(function () {
      that.initSwitch()
      that.isSwitch = true
      clearTimeout(timer)
      timer = null
    }, 1)

    modal.show()
  }

  modalLookClose(modal) {
    modal.hide()
  }
  RecordList: any = []
  //变更记录
  changeRecord(row, modal) {
    var that = this
    this.RecordList = []
    this.jsonApiService.http('repairPlan/getRepairPlanLogById.html', 'id=' + row.id).subscribe(data => {
      if (data.success) {
        for (var i = 0; i < data.data.length; i++) {
          var companyNameAttr = []
          for (var j = 0; j < data.data[i].companyArrays.length; j++) {
            companyNameAttr.push(data.data[i].companyArrays[j].companyName)
          }
          data.data[i].companyNameAttr = companyNameAttr.join(',')
        }

        this.RecordList = data.data
        for (let item of this.RecordList) {
          for (let lis of item.repairPlans) {
            lis.price = lis.price / 100
            lis.discountPrice = lis.discountPrice / 100
          }
        }

        modal.show()
        // let timer = setTimeout(function () {
        //     that.initSwitch();
        //     that.isSwitch = true
        //     clearTimeout(timer)
        //     timer = null
        // }, 151)
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  showDetailChange(value) {
    var that = this
    this.repairPonitFrom.showDetail = value
    if (value == 1 && that.isSwitch == false) {
      let timer = setTimeout(function () {
        that.initSwitch()
        that.isSwitch = true
        clearTimeout(timer)
        timer = null
      }, 1)
    } else {
      that.isSwitch = false
    }
  }

  needCheckChange(value) {
    this.repairPonitFrom.needCheck = value
  }
  needAppointmentChange(value) {
    this.repairPonitFrom.needAppointment = value
  }
  //支付方式change回调
  lockStatusChange(val) {
    console.log(val)
    this.repairPonitFrom.payWay = val
  }
}
